<?php

/**
 * @Author: CraspHB彬
 * @Date:   2018-03-01 14:31:57
 * @Email:   646054215@qq.com
 * @Last Modified time: 2018-03-29 11:23:36
 */
namespace app\admin\model;

use think\Model;
use think\Db;
use app\admin\model\Hooks as HooksModel;
/**
 * 后台插件模型
 * @package app\admin\model
 */
class Addons extends Model{
	/**
	 * 获取插件列表
	 * @param  string $addon_dir [description]
	 * @return [type]            [description]
	 */
    public function get_addons_list($addon_dir = ''){
        if(!$addon_dir) $addon_dir = ADDON_PATH;
            
        $dirs = array_map('basename',glob($addon_dir.'*', GLOB_ONLYDIR));
        if($dirs === FALSE || !file_exists($addon_dir)){
            $this->error = '插件目录不可读或者不存在';
            return FALSE;
        }
    		$addons			=	array();
    		$where['name']	=	array('in',$dirs);
    		$list			=	self::where($where)->select();
    		foreach($list as $addon){
    			$addon['uninstall']		=	0;
    			$addons[strtolower($addon['name'])]	=	$addon;
    		}
        foreach ($dirs as $value) {
            if(!isset($addons[strtolower($value)])){
      				$class = get_addon_class($value);
      				if(!class_exists($class)){ // 实例化插件失败忽略执行
      					return -2;
      					continue;
      				}
              $obj    =   new $class;
      				$addons[$value]	= $obj->info;
      				if($addons[$value]){
      					$addons[$value]['uninstall'] = 1;
                  unset($addons[$value]['status']);
      				}
    			}
        }
        return array_reverse($addons);
    }
    /**
     *插件安装
     * @param  [type] $addon_name [description]
     * @return [type]             [description]
     */
    public function install($addon_name){
    	$class  =  get_addon_class($addon_name);
    //dump($class);die;
        if(!class_exists($class))
            $this->error = '插件不存在';
        $addons  =   new $class;
        $info = $addons->info;
        if(!$info || !$addons->checkInfo())//检测信息的正确性
            $this->error = '插件信息缺失';
        $install_flag   =   $addons->install();
        if(!$install_flag){
            $this->error = '执行插件预安装操作失败';
        }
        if(! isset($info['has_adminlist'])) $info['has_adminlist'] = 0;
        $info['addtime'] = time();     
        if(Db::name('addons')->insert($info)){
            $config         =  ['config'=>json_encode($addons->getConfig())];
            Db::name('addons')->where('name',$addon_name)->update($config);
            $hooksModel = new HooksModel();
            $hooks_add  = $hooksModel->add_hooks($addon_name);
            if($hooks_add){
                return true;
            }else{
                Db::name('addons')->where('name',$addon_name)->delete();
                $this->error = '更新钩子处插件失败,请卸载后尝试重新安装';
            }

        }else{
            $this->error = '写入插件数据失败';
        }
        //执行sql文件
        $sql_file = realpath(ADDON_PATH.$addon_name.'/install.sql');
        if (file_exists($sql_file)) {
        	  //数据表前缀
        	  $prefix = $addons->prefix;
              execute_file_sql($sql_file,$prefix);
        }
        return true;       
    }
    /**
     * 插件卸载
     * @return [type] [description]
     */
    public function uninstall($addon_name){
        $class =  get_addon_class($addon_name);
        if(!$addon_name || !class_exists($class))
            $this->error = '插件不存在';
        $addons =   new $class;
        $uninstall_flag =   $addons->uninstall();
        if(!$uninstall_flag)
            $this->error= '执行插件预卸载操作失败';
        $hooksmodel = new HooksModel();
        $hooks_update   =  $hooksmodel->remove_hooks($addon_name);
        if($hooks_update === false){
            $this->error = '卸载插件所挂载的钩子数据失败';
        }
        $delete = self::where('name',$addon_name)->delete();
        if($delete === false){
            $this->error = '卸载插件失败';
        }else{
            return true;
        }
    }
    /**
     * 插件启用禁用
     * @param [type] $id [description]
     */
    public function set_status($id){
       $status = self::where('id',$id)->value('status');
       if($status == 1){
          if(self::where('id',$id)->setField('status',0)){
             $res = ['success'=>1,'msg'=>'已禁用'];
          }else{
             $res = ['success'=>0,'msg'=>'操作失败'];
          }
       }else{
         if(self::where('id',$id)->setField('status',1)){
             $res = ['success'=>1,'msg'=>'已启用'];
          }else{
             $res = ['success'=>0,'msg'=>'操作失败'];
          }
       }
       return $res;
    }
    public function config($addon_name){
       $addon  =   Db::name('addons')->where('name',$addon_name)->find();
        if(!$addon) $this->error = '插件未安装';
        $addon_class = get_addon_class($addon_name);
        if(!class_exists($addon_class))
           $this->error = "插件{$addon_name}无法实例化";
        $data  =   new $addon_class;
        $addon['addon_path'] = $data->addons_path;
        $addon['custom_config'] = $data->custom_config;
        $db_config = $addon['config'];
        $addon['config'] = include $data->config_file;
        if($db_config){
            $db_config = json_decode($db_config, true);
            foreach ($addon['config'] as $key => $value) {
                if($value['type'] != 'group'){
                    $addon['config'][$key]['value'] = $db_config[$key];
                }else{
                    foreach ($value['options'] as $gourp => $options) {
                        foreach ($options['options'] as $gkey => $value) {
                            $addon['config'][$key]['options'][$gourp]['options'][$gkey]['value'] = $db_config[$gkey];
                        }
                    }
                }
            }
        }
        $res = ['addon'=> $addon,'custom_config'=>''];       
        if($addon['custom_config']) $res['custom_config'] = $addon['addon_path'].$addon['custom_config'];
        return $res;
    }
}